//
//  WNAuthViewController.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/25.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit
import SVProgressHUD

//  新浪微博表示应用的唯一id
let AppKey = "3804681419"
//  AppSecret是app秘钥
let AppSecret = "7dd3347597df04db2a7d7f0abedcc832"
//  授权成功回调地址
let Redirect_uri = "http://www.baidu.com"

class WNAuthViewController: UIViewController {

    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self
        view = webView

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupNavUI()
        
        loadLogin()
        
    }

    //  设置导航栏按钮
    private func setupNavUI() {
        //  左侧导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        //  设置标题
        navigationItem.title = "微博登录"
        //  右侧导航栏按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    func loadLogin(){
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        
        let url = URL(string: urlStr)
        
        webView.loadRequest(URLRequest(url:url!))
    }
    
    //  MARK: --导航栏按钮点击事件处理
    @objc private func cancelAction() {
        self.dismiss(animated: true, completion: nil)
    }

    
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15688879979';document.getElementById('passwd').value = 'lch199309';document.getElementById('passwd').focus();")
    }
    
//    //获取令牌方法
//    func requestAccessToken (code : String){
//        
//        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            
//            if error != nil
//            {
//                print(error)
//                
//                return
//            }
//            
//            let dic = response
//            let userAccount = WNUserAccount(dic: dic as! [String : Any])
//            
//            self.requestUserInfo(userAccount: userAccount)
//        }
//    }
//    
//    //获取用户数据方法
//    func requestUserInfo(userAccount : WNUserAccount){
//        
//        let token = userAccount.access_token
//        
//        let uid = userAccount.uid
//        
//        HMNetworkTools.sharedTools.requestUserinfo(access_token: token!, uid: uid) { (response, error) in
//            
//            if error != nil{
//    
//                print(error)
//                return
//            }
//            
//            let dic = response as! [String : Any]
//            
//            userAccount.name = dic["name"] as? String
//            
//            userAccount.avatar_large = dic["avatar_larged"] as? String
//            
//            print(userAccount.name)
//            
//            //保存用户对象
//            userAccount.saveUserAccount()
//        }
//    }

}

// MARK:----WebViewDelegate方法
extension WNAuthViewController : UIWebViewDelegate
{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.url?.absoluteString)
        
        if request.url?.absoluteString.hasPrefix(Redirect_uri) == true {
            
            //以授权回调地址开头 query url?后面的参数
            if let query = request.url?.query , query.hasPrefix("code=") {
                
                let code = query.substring(from: "code=".endIndex)
                
//                requestAccessToken(code: code)
                WNUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess : Bool) in
                    if isSuccess {
                        
                        print("成功")
                        self.dismiss(animated: false, completion: { 
                            
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)

                        })
                        
                    }else{
                        print("失败")

                    }
                })
                
            }else{
                
                self.dismiss(animated: true, completion: nil)
            }
            
            return false
            
        }
        
        //允许加载这次请求
        return true
    }
    
    //加载延迟菊花动画
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()

    }
    
}













